package com.itdianzi.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ctc.wstx.util.StringUtil;
import com.github.pagehelper.PageInfo;
import com.itdianzi.controller.base.BaseController;
import com.itdianzi.domain.cargo.PackingExample;
import com.itdianzi.domain.cargo.ShippingOrderExample;
import com.itdianzi.domain.cargo.ShippingOrder;

import com.itdianzi.export_common.common.utils.DownloadUtil;
import com.itdianzi.service.cargo.PackingService;
import com.itdianzi.service.cargo.ShippingOrderService;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/shipping")
public class ShippingOrderController extends BaseController {

    @Reference
    private ShippingOrderService shippingOrderService;

    @Reference
    private PackingService packingService;


    /*
     *   分页展示所有的委托单
     * */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "5") int size) {
        ShippingOrderExample shippingOrderExample = new ShippingOrderExample();
        shippingOrderExample.setOrderByClause("CREATE_TIME DESC");
        ShippingOrderExample.Criteria shippingOrderExampleCriteria = shippingOrderExample.createCriteria();
        shippingOrderExampleCriteria.andCompanyIdEqualTo(companyId);
        PageInfo pageInfo = shippingOrderService.findAll(shippingOrderExample, page, size);
        System.err.println(pageInfo);
        request.setAttribute("page", pageInfo);
        return "cargo/shipping/shipping-list";
    }


    /*
     *  跳转到新建页面
     *          跳转之前，将装箱单的数据分页展示
     * */
    @RequestMapping("/toAdd")
    public String toAdd(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "5") Integer size) {
        PackingExample packingExample = new PackingExample();
        packingExample.setOrderByClause("create_Time desc");
        PackingExample.Criteria packingExampleCriteria = packingExample.createCriteria();
        packingExampleCriteria.andCompanyIdEqualTo(super.companyId);
        PageInfo pageInfo = packingService.findByPage(packingExample, page, size);
        request.setAttribute("page", pageInfo);
        return "cargo/shipping/shipping-add";
    }


    /*
     *   新建委托单的方法
     * */
    @RequestMapping("/save")
    public String save(ShippingOrder shippingOrder) {
        shippingOrder.setCompanyId(companyId);
        shippingOrder.setCompanyName(companyName);
        shippingOrder.setCreateBy(loginUser.getUserName());
        shippingOrder.setCreateDept(loginUser.getDeptName());
        shippingOrderService.save(shippingOrder);

        return "redirect:/cargo/shipping/list.do";
    }


    /*
     *   跳转到修改页面
     * */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        request.setAttribute("shippingOrder", shippingOrder);
        return "cargo/shipping/shipping-update";
    }


    /*
     *   修改的方法
     * */
    @RequestMapping("/Update")
    public String Update(ShippingOrder shippingOrder) {
        shippingOrderService.update(shippingOrder);
        return "redirect:/cargo/shipping/list.do";
    }


    /*
     *   根据委托单id删除委托单
     * */
    @RequestMapping("/delete")
    public String delete(String id) {
        System.out.println(id);
        shippingOrderService.delete(id);
        return "redirect:/cargo/shipping/list.do";
    }


    /*
     *   提交的方法：
     *      草稿：state=0;
     *      已上报：state=1;
     *      已报运：state=2;
     * */
    @RequestMapping("/submit")
    public String submit(String id) {
        //1：根据id查询对象，修改id，保存到数据库
        //2: 利用mybatis生成update方法
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        shippingOrder.setState(1);//提交状态
        shippingOrderService.update(shippingOrder);
        return "redirect:/cargo/shipping/list.do";
    }

    /*
     *  取消的方法：将状态state=1修改成state=0
     * */
    @RequestMapping("/cancel")
    public String cancel(String id) {
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        shippingOrder.setState(0);
        shippingOrderService.update(shippingOrder);
        return "redirect:/cargo/shipping/list.do";
    }

    /*
    *   打印单个委托单的Excel
    * */
    @RequestMapping("/shippingOrderExcel")
    public String shippingOrderExcel(String id) throws IOException {


        //1:查询字段(根据隐藏字段)
        ShippingOrder shippingOrder = shippingOrderService.findById(id);

        //2:从数据库查询到数据后,要进行转换数据打印
        //读取文件：重点
        //类加载器只能加载src下的内容
        //servletContext对象，可以加载webapp下的所有的资源
        ServletContext servletContext = session.getServletContext();
        InputStream is = servletContext.getResourceAsStream("/make/xlsprint/tOUTPRODUCT2.xlsx");
        //2.1:工作簿:使用工作簿的构造方法，直接在创建的时候，将模板传递到工作簿对象中
        Workbook wb = new XSSFWorkbook(is);
        //2.2:获得表，不用创建了
        Sheet sheet = wb.getSheetAt(0);
        //2.3:创建Excel的大标题
        Row row = sheet.getRow(0);
        //获得第一个单元格即可
        Cell cell = row.getCell(1);
        //传入的是inputDate,这里动态拼接

        cell.setCellValue("委托单"+shippingOrder.getShippingOrderId()+"的报表");


        //2.4：创建Excel的小标题
        //2.4.1：准备标题的文字
        String[] headNames = {
                "",
                "装箱单的id",
                "海运/空运",
                "货主",
                "装运港",
                "卸货港",
                "装期",
                "效期",
                "是否分批",
                "是否转船",
                "运输要求",
                "转船港"};

        //2.4.2小标题
        row = sheet.getRow(1);
        //2.4.3循环创建小标题
        for (int i=1;i<headNames.length;i++) {
            cell = row.getCell(i);//创建每一个单元格
            cell.setCellValue(headNames[i]);//设置值
        }

        //构建数据之前，必须得先将表格中的样式复制出来
        CellStyle[] cellStyles = new CellStyle[12];//提前设置样式的长度
        row = sheet.getRow(2);//获得第三行的模板对象
        short lastCellNum = row.getLastCellNum();
        //循环获得样式
        //要是从1开始，那么就得判断获得单元格是否有值，否则就会为null
        for (int i = 1; i < lastCellNum; i++) {
            //获取到每个单元格的样式，并存入数组,方便在接下来对我们的样式进行赋值
            cellStyles[i] = row.getCell(i).getCellStyle();
        }

        //2.5：构建数据：一行数据一个对象，遍历list即可。

        row = sheet.createRow(2);//创建每一行,index用来模拟i,表示的是Excel表各中的每一行数据
            //"装箱单的id"

        cell = row.createCell(1);
        cell.setCellValue(shippingOrder.getShippingOrderId());
        cell.setCellStyle(cellStyles[1]);
            //"海运/空运"

        cell = row.createCell(2);
        cell.setCellValue(shippingOrder.getOrderType());
        cell.setCellStyle(cellStyles[2]);
            //"货主"

        cell = row.createCell(3);
        cell.setCellValue(shippingOrder.getShipper());
        cell.setCellStyle(cellStyles[3]);
            //"数量"

        cell = row.createCell(4);
        cell.setCellValue(shippingOrder.getPortOfLoading());
        cell.setCellStyle(cellStyles[4]);
            //"工厂"

        cell = row.createCell(5);
        cell.setCellValue(shippingOrder.getPortOfDischarge());
        cell.setCellStyle(cellStyles[5]);
            //"工厂交期"

        cell = row.createCell(6);
        cell.setCellValue(shippingOrder.getLoadingDate());
        cell.setCellStyle(cellStyles[6]);
            //"船期"

        cell = row.createCell(7);
        cell.setCellValue(shippingOrder.getLimitDate());
        cell.setCellStyle(cellStyles[7]);
            //"贸易条款"

        cell = row.createCell(8);
        cell.setCellValue(shippingOrder.getIsBatch());
        cell.setCellStyle(cellStyles[8]);

        cell = row.createCell(9);
        cell.setCellValue(shippingOrder.getIsTrans());
        cell.setCellStyle(cellStyles[9]);

        cell = row.createCell(10);
        cell.setCellValue(shippingOrder.getSpecialCondition());
        cell.setCellStyle(cellStyles[10]);

        cell = row.createCell(11);
        cell.setCellValue(shippingOrder.getPortOfTrans());
        cell.setCellStyle(cellStyles[11]);


        //3：下载---->用response
        //创建输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //将工作簿转换成字节流
        wb.write(byteArrayOutputStream);
        //使用工具类，独到的数据下载
        DownloadUtil downloadUtil = new DownloadUtil();
        downloadUtil.download(byteArrayOutputStream, response, "委托单.xlsx");

        return "redirect:/cargo/shipping/list.do";
    }
}
